package model

import (
	"vueBasic/app/admin/filter"
	"vueBasic/extend/conv"
	"vueBasic/global"
)

var RoleM = new(roleModel)

type roleModel struct {
	Id          uint   `form:"id" json:"id"`
	Title       string `form:"title" json:"title"`
	Description string `form:"description" json:"description"`
	Status      int    `form:"status" json:"status"`
	AddTime     int64  `form:"add_time" json:"add_time"`
}

func (*roleModel) TableName() string {
	return global.CONF.Database.Db.Prefix + "role"
}

// 根据标题查找吃否存在角色
func (*roleModel) GetRoleByTitle(title string) (*roleModel, error) {
	var role roleModel
	err := global.DB.Model(&roleModel{}).Where("title=?", title).Limit(1).First(&role).Error
	if err != nil {
		return nil, err
	}
	return &role, nil
}

// 添加
func (*roleModel) Add(req *filter.AdminRoleAddReq) (uint, error) {
	entity := roleModel{}
	entity.Title = req.Title
	entity.Status = req.Status
	entity.Description = req.Description
	entity.AddTime = conv.NowUnix()
	if err := global.DB.Create(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

// 获取列表数据
func (*roleModel) GetList(where string, page int, limit int) ([]*filter.AdminRoleListRes, int64, error) {

	var (
		list  []*filter.AdminRoleListRes
		count int64
	)
	query := global.DB.Model(&roleModel{})
	if err := query.Where(where).Limit(limit).Offset((page - 1) * limit).Order("id ASC").Find(&list).Error; err != nil {
		return nil, 0, err
	}
	//获取总条数
	query.Where(where).Count(&count)
	return list, count, nil

}

// 根据ID查询角色详情
func (*roleModel) GetRoleById(req *filter.AdminRoleGetUpdateInfoReq) (*filter.AdminRoleListRes, error) {
	var info *filter.AdminRoleListRes
	err := global.DB.Model(&roleModel{}).Where("id=?", req.Id).Limit(1).First(&info).Error
	if err != nil {
		return nil, err
	}
	return info, nil
}

// 更新
func (*roleModel) Update(req *filter.AdminRoleUpdateReq) (uint, error) {
	entity := roleModel{Id: req.Id}
	global.DB.First(&entity)
	entity.Title = req.Title
	entity.Status = req.Status
	entity.Description = req.Description
	if err := global.DB.Save(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*roleModel) UpdateExt(req map[string]interface{}) error {
	query := global.DB.Model(&roleModel{})
	if err := query.Where("id=?", req["id"]).Updates(req).Error; err != nil {
		return err
	}
	return nil
}

// 删除
func (*roleModel) Delete(ids []string) (uint, error) {
	query := global.DB.Where("id IN ?", ids)
	err := query.Delete(&roleModel{}).Error
	if err != nil {
		return 0, err
	}
	return 1, nil
}
